package com.sh.pangea.dsa.Utils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.sh.pangea.dsa.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 用于版本更新的版本工具类
 * 
 * @author smile
 * 
 */
public class AppVersionUtil {

	private static AlertDialog alertDialog;

	/**
	 * 获取当前应用程序的版本号
	 * 
	 * @param mContext
	 * @return
	 */
	public static String getVersionName(Context mContext) {
		// 获取手机的包管理者
		String versionName = "";
		 try {
		        PackageManager manager = mContext.getPackageManager();
		        PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
		        versionName = info.versionName;
		    } catch (Exception e) {
			 Log.w("",e.getLocalizedMessage());
		    }
		 return versionName;
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public static int getVersion(Context mContext) {
		int versionCode = 100;
		try {
			PackageManager manager = mContext.getPackageManager();
			PackageInfo info = manager.getPackageInfo(
					mContext.getPackageName(), 0);
			versionCode = info.versionCode;
		} catch (Exception e) {
			Log.w("",e.getLocalizedMessage());
		}
		return versionCode;
	}

	/**
	 * 从XML中获取app name
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppNameFromStringXML(Context context) {
		String verName = context.getResources().getText(R.string.app_name)
				.toString();
		return verName;
	}

	/**
	 * 更新提示框
	 * 
	 * @param context
	 * @param msg
	 * @param positiveListener
	 * @param negativeListener
	 */
	public static void showSelectDialog(Context context, String msg,
										DialogInterface.OnClickListener positiveListener,
										DialogInterface.OnClickListener negativeListener) {
		if (null != alertDialog) {
			alertDialog.dismiss();
		}
		alertDialog = new AlertDialog.Builder(context).setMessage(msg)
				.setTitle("温馨提示").setPositiveButton("是", positiveListener)
				.setNegativeButton("否", negativeListener).create();
		alertDialog.show();
	}

	/** 检测用户是否安装微信 **/
	public static boolean checkWeChat(Context context) {
		boolean istrue = false;
		ArrayList<String> list = getUserAppname(context);
		if (list != null) {
			for (String s : list) {
				if ("微信".equals(s)) {
					istrue = true;
					break;
				}
			}
		}
		return istrue;
	}

	public static ArrayList<String> getUserAppname(Context context) {
		ArrayList<String> apps = new ArrayList<String>();
		List<PackageInfo> list = context.getPackageManager()
				.getInstalledPackages(0);
		for (int i = 0; i < list.size(); i++) {
			PackageInfo info = list.get(i);
			String appname = info.applicationInfo
					.loadLabel(context.getPackageManager()).toString().trim();
			apps.add(appname);
		}
		return apps;
	}

}
